package com.ksl.kinglockguard.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ksl.kinglockguard.R;
import com.ksl.kinglockguard.activity.base.AbstractActivity;
import com.ksl.kinglockguard.data.UserCountHabit;
import com.ksl.kinglockguard.network.NetworkTask;
import com.ksl.kinglockguard.network.appupdate.AppUpdateService;
import com.ksl.kinglockguard.network.appupdate.UpdateAppTaskListener;
import com.ksl.kinglockguard.widget.common.CustomProgressDialog;
import com.ksl.kinglockguard.widget.common.MyTitleView;
import com.ksl.kinglockguard.widget.common.MyTitleView.MenuImageResourceListener;
import com.lsk.open.core.MyLog;
import com.lsk.open.core.net.NetConnectTask;
import com.lsk.open.core.net.NetHeadUtils;
import com.lsk.open.core.utils.ProductInfoUtils;

public class SettingPageActivity extends AbstractActivity implements MenuImageResourceListener{

	private ListView settingList;
	SettingAdapter adapter;
	MyTitleView myTitleView;
	private TextView tv_vname;
	public static final int SETTING_PAGE_NUM = 2;
	private static final String MI_UI_STR = "ro.miui.ui.version.name";
	private LinearLayout checkUpdate;
	private RelativeLayout closeSysScreen;
	private static final Handler handler = new Handler();
	
	CustomProgressDialog mProgressDialog;

	private boolean toCloseSys;
	private boolean isMiui;
	private boolean isMeizu;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MyLog.i("jyh", "~~~~~~~SettingPageActivity onCreate()~~~~~~~~");
		setContentView(R.layout.setting_page_activity);
		InitView();
		InitListener();
		
		//AnalyizeDrawabletool.clearAppDrawableCache(getApplicationContext());
	}

	private void InitView() {
		InitTitleBar();
		checkUpdate = (LinearLayout) findViewById(R.id.check_update);
		closeSysScreen = (RelativeLayout) findViewById(R.id.close_sysscreen);
		tv_vname=(TextView) findViewById(R.id.tv_vname);
		tv_vname.setText(getResources().getString(R.string.v_name, ProductInfoUtils.getVersionName(getApplicationContext())));
//		settingList = (ListView) findViewById(R.id.settingList);
//		adapter = new SettingAdapter(this);
//		settingList.setAdapter(adapter);
	}

	private void InitTitleBar() {
		myTitleView = new MyTitleView(this, false);
		myTitleView.setTitle(getString(R.string.lock_settings_title));
		myTitleView.setCenterTitleVisibility(true);
		myTitleView.setLaybackTitleVisibility(false);
		myTitleView.setCenterTitleText("");
		myTitleView.setMenuImageResourceListener(this);
	}

	private void InitListener() {
		checkUpdate.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				MyLog.i("wmm", "update " + System.currentTimeMillis());
				if(NetHeadUtils.isNetWorking(getApplicationContext())){
					MyLog.i("jyh", "~~~~~~~checkUpdate~~~~~~~~~");
					checkUpdate();
				} else{
					Toast.makeText(getApplicationContext(), R.string.lock_network_error_no_net_tip, Toast.LENGTH_SHORT ).show();
				}
				UserCountHabit.setUserCount(SettingPageActivity.this, UserCountHabit.CHECK_UPDATE);
			}
		});
		closeSysScreen.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				MyLog.i("wmm", "closeSysScreen " + System.currentTimeMillis());
				UserCountHabit.setUserCount(SettingPageActivity.this, UserCountHabit.CLOSE_SYSTEM_LOCK);
				toCloseSys = true;
				closeSysScreen();
			}
		});
//		settingList.setOnItemClickListener(new OnItemClickListener() {
//			@Override
//			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
//					long arg3) {
//				switch (arg2) {
//				case 0:
//					if(NetworkUtil.isNetWorking(getApplicationContext())){
//						MyLog.i("jyh", "~~~~~~~checkUpdate~~~~~~~~~");
//						checkUpdate();
//					} else{
//						Toast.makeText(getApplicationContext(), R.string.lock_network_error_no_net_tip, Toast.LENGTH_SHORT ).show();
//					}
//					UserCountHabit.setUserCount(getApplicationContext(), UserCountHabit.CHECK_UPDATE);
//					break;
//
//				case 1:
//					closeSysScreen();
//					break;
//
//				case 2:
//					break;
//				}
//			}
//		});
	}

	private void closeSysScreen(){
		if(android.os.Build.BRAND.equals("Xiaomi")){//小米MIUI
			isMiui = true;
			isMeizu = false;
			Intent intent = new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS); 
			startActivity(intent);
//			handler.postDelayed(miuiMaskActRunn, 20);
		}else if(android.os.Build.BRAND.equals("Meizu")){//魅族
			isMiui = false;
			isMeizu = true;
			Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
			startActivity(intent);
		}else{
			isMiui = false;
			isMeizu = false;
			Intent intent = new Intent("/");
			ComponentName cm = new ComponentName("com.android.settings","com.android.settings.ChooseLockGeneric");
			intent.setComponent(cm);
			startActivityForResult(intent, 0);
//			handler.postDelayed(maskActRunn, 20);
		} 
		MyLog.i("jyh", "~~~~~~~brand is "+android.os.Build.BRAND);
	}
	
	Runnable maskActRunn = new Runnable() {
    	
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		MyLog.i("jyh", "~~~~~~~~~~~~~~runnable starts acting~~~~~~~~~~~~");
    		startActivity(new Intent(SettingPageActivity.this, MaskActivity.class));
    	}
    };
    
    Runnable miuiMaskActRunn = new Runnable() {
    	
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		MyLog.i("jyh", "~~~~~~~~~~~~~~miui runnable starts acting~~~~~~~~~~~~");
    		startActivity(new Intent(SettingPageActivity.this, MiuiMaskActivity.class));
    	}
    };
    
    Runnable meizuMaskActRunn = new Runnable() {
    	
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		MyLog.i("jyh", "~~~~~~~~~~~~~~miui runnable starts acting~~~~~~~~~~~~");
    		startActivity(new Intent(SettingPageActivity.this, MeizuMaskActivity.class));
    	}
    };
    
	protected void checkUpdate() {
		if(AppUpdateService.isDownloadingUpdateApk){
			Toast.makeText(getApplicationContext(),  R.string.lock_update_toast_downloading_update_apk_tip, Toast.LENGTH_SHORT).show();
			return;
		}
		if(!NetHeadUtils.isNetWorking(this)){
			MyLog.i("jyh", "~~~~~~~!NetworkUtil.isNetWorking(this)~~~~~~~~~");
			Toast.makeText(getApplicationContext(),  R.string.lock_network_error_no_net_tip, Toast.LENGTH_SHORT).show();
			return;
		}
		mProgressDialog = new CustomProgressDialog(this,getString(R.string.lock_update_loading_check));
//		mProgressDialog.setOnDismissListener(new OnDismissListener() {
//			@Override
//			public void onDismiss(DialogInterface dialog) {
//				isCheckingUpdate = false;
//			}
//		});
		
		final NetConnectTask networkTask = NetworkTask
				.requestUpdateMyApp(getApplicationContext());
		
		networkTask.setListener(new UpdateAppTaskListener(SettingPageActivity.this, UpdateAppTaskListener.NOTIFY_TYPE_DIALOG, mProgressDialog));
		mProgressDialog.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				if(!networkTask.isCancelled())
					networkTask.cancel(false);
			}
		});
		mProgressDialog.show();
	}
	
	public class SettingAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private final int TYPE_1 = 0;
		private final int TYPE_2 = 1;
		private final int TYPE_3 = 2;

		public SettingAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return SETTING_PAGE_NUM;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public int getItemViewType(int position) {
			int p = position;
			if (p == 0)
				return TYPE_1;
			else
				return TYPE_2;
			/*else
				return TYPE_3;*/
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder1 holder1 = null;
			ViewHolder2 holder2 = null;
			ViewHolder3 holder3 = null;
			int type = getItemViewType(position);
			if (convertView == null) {
				switch (type) {
				case TYPE_1:
					convertView = mInflater.inflate(R.layout.lock_check_update_item,
							parent, false);
					holder2 = new ViewHolder2();
					holder2.checkUpdateText = (TextView) convertView
							.findViewById(R.id.checkUpdateText);
					convertView.setTag(holder2);
					break;
					
				case TYPE_2:
					convertView = mInflater.inflate(R.layout.lock_close_sysscreen, parent,
							false);
					holder1 = new ViewHolder1();
					holder1.closeInfo = (TextView) convertView
							.findViewById(R.id.close_info);
					holder1.arrow = (ImageView) convertView
							.findViewById(R.id.arrow);
					convertView.setTag(holder1);
					break;
					
				case TYPE_3:
					convertView = mInflater.inflate(R.layout.lock_about_item,
							parent, false);
					holder3 = new ViewHolder3();
					holder3.aboutText = (TextView) convertView
							.findViewById(R.id.aboutText);
					holder3.goToPage = (ImageView) convertView
							.findViewById(R.id.goToPage);
					convertView.setTag(holder3);
					break;
				default:
					break;
				}
//				convertView.setBackgroundResource(R.drawable.lock_list_item_color_bg);

			} else {
				switch (type) {
				case TYPE_1:
					holder1 = (ViewHolder1) convertView.getTag();
					break;
				case TYPE_2:
					holder2 = (ViewHolder2) convertView.getTag();
					break;
				case TYPE_3:
					holder3 = (ViewHolder3) convertView.getTag();
					break;
				}
			}

			return convertView;
		}

		public void UpdateData() {
			notifyDataSetChanged();
		}

		public class ViewHolder1 {
			TextView closeInfo;
			ImageView arrow;
		}

		public class ViewHolder2 {
			TextView checkUpdateText;
		}

		public class ViewHolder3 {
			TextView aboutText;
			ImageView goToPage;
		}
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
	@Override
	protected void onStop() {
		super.onStop();
		if(toCloseSys){
			if(isMiui){
				handler.postDelayed(miuiMaskActRunn, 1);
			}else if(isMeizu){
				handler.postDelayed(meizuMaskActRunn, 1);
			}else{
				handler.postDelayed(maskActRunn, 1);
			}
		}
		toCloseSys = false;
	}

	@Override
	public void setMenuImageResource(ImageView menu_img, int id) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setImageBtnGray(ImageView menu_img, int id) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setImageBtnNormal(ImageView menu_img, int id) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void goBackPreviousPage(boolean parentPage) {
		// TODO Auto-generated method stub
		Intent data=new Intent();
		setResult(LockMainActivity.BACK_RROM_SETTING_PAGE, data);
		this.finish();
		overridePendingTransition(R.anim.enter_alpha, R.anim.leave_alpha);
		MyLog.i("jyh1", "~~~~go back from setting page~~~~~~");
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent data=new Intent();
			setResult(2, data);
			this.finish();
			overridePendingTransition(R.anim.enter_alpha, R.anim.leave_alpha);
			return true;
		}else{
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	public String getUserHabitKey() {
		// TODO Auto-generated method stub
		return null;
	}
}
